<template>
	<view class="collections-page">
		<!-- 下拉刷新容器 -->
		<scroll-view scroll-y class="scroll-container" @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh" @refresherrestore="onRestore">

			<!-- 骨架屏 -->
			<view class="skeleton-container" v-if="loading && collections.length === 0">
				<view class="skeleton-item" v-for="i in 3" :key="i">
					<view class="skeleton-content">
						<view class="skeleton-title skeleton-animate"></view>
						<view class="skeleton-meta">
							<view class="skeleton-text skeleton-animate"></view>
							<view class="skeleton-text skeleton-animate"></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 收藏列表 -->
			<view class="collections-list" v-else-if="collections.length > 0">
				<view class="collection-item" v-for="post in collections" :key="post.postId"
					@click="handlePostClick(post.postId)">
					<!-- 帖子信息 -->
					<view class="post-info">
						<text class="post-title">{{ post.title }}</text>
						<view class="post-meta">
							<view class="meta-item">
								<up-icon name="account" size="12" color="#999999"></up-icon>
								<text class="meta-text">{{ post.nickname }}</text>
							</view>
							<view class="meta-item">
								<up-icon name="eye" size="12" color="#999999"></up-icon>
								<text class="meta-text">{{ post.viewCount }}</text>
							</view>
							<view class="meta-item">
								<up-icon name="clock" size="12" color="#999999"></up-icon>
								<text class="meta-text">{{ formatTime(post.collectTime) }}</text>
							</view>
						</view>
					</view>

					<!-- 封面图 -->
					<image v-if="post.image && post.image.length > 0" :src="post.image[0]" mode="aspectFill"
						class="post-cover" lazy-load></image>

					<!-- 取消收藏按钮 -->
					<view class="cancel-btn" @click.stop="handleCancelCollect(post.postId)">
						<up-icon name="star-fill" size="16" color="#ff9f1c"></up-icon>
					</view>
				</view>

				<!-- 加载更多 -->
				<view class="load-more" v-if="hasMore">
					<up-loading-icon v-if="loadingMore" size="20" />
					<text v-else class="load-more-text">上拉加载更多</text>
				</view>
				<view class="no-more" v-else>
					<text class="no-more-text">没有更多了</text>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-else-if="!loading && collections.length === 0">
				<up-icon name="star" size="80" color="#cccccc"></up-icon>
				<text class="empty-text">还没有收藏内容</text>
				<text class="empty-hint">快去收藏喜欢的帖子吧～</text>
				<up-button type="primary" size="small" @click="handleGoPosts" color="#36d399" class="go-btn">
					去逛逛
				</up-button>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		mockGetPosts,
		mockUncollectPost
	} from '../../server/mock.js';
	import showToast from '../../utils/showToast.js';

	// 状态
	const loading = ref(true);
	const refreshing = ref(false);
	const loadingMore = ref(false);
	const hasMore = ref(true);
	const collections = ref([]);
	const pageNum = ref(1);
	const pageSize = ref(10);

	/**
	 * 加载收藏列表
	 */
	const loadCollections = async () => {
		try {
			// 模拟获取当前用户的收藏列表
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo) {
				showToast('请先登录', 'none');
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1000);
				return;
			}

			// 调用 Mock API（实际应该调用获取用户收藏的接口）
			const res = await mockGetPosts({
				pageNum: pageNum.value,
				pageSize: pageSize.value,
				userId: userInfo.userId // 模拟筛选用户收藏的帖子
			});

			if (res.code === 200) {
				const newData = res.data || [];

				if (pageNum.value === 1) {
					collections.value = newData;
				} else {
					collections.value = [...collections.value, ...newData];
				}

				// 添加收藏时间（模拟）
				collections.value = collections.value.map((item, index) => ({
					...item,
					collectTime: Date.now() - (index * 86400000) // 模拟不同的收藏时间
				}));

				hasMore.value = newData.length >= pageSize.value;
			} else {
				showToast(res.message || '加载失败', 'error');
			}
		} catch (error) {
			console.error('加载收藏失败:', error);
			showToast('网络错误', 'error');
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 格式化时间
	 */
	const formatTime = (timestamp) => {
		const now = Date.now();
		const diff = now - timestamp;
		const day = 24 * 60 * 60 * 1000;

		if (diff < day) {
			return '今天';
		} else if (diff < day * 2) {
			return '昨天';
		} else if (diff < day * 7) {
			return Math.floor(diff / day) + '天前';
		} else {
			const date = new Date(timestamp);
			return `${date.getMonth() + 1}/${date.getDate()}`;
		}
	};

	/**
	 * 下拉刷新
	 */
	const onRefresh = async () => {
		refreshing.value = true;
		pageNum.value = 1;
		hasMore.value = true;

		try {
			await loadCollections();
		} finally {
			setTimeout(() => {
				refreshing.value = false;
			}, 300);
		}
	};

	/**
	 * 刷新恢复
	 */
	const onRestore = () => {
		refreshing.value = false;
	};

	/**
	 * 加载更多
	 */
	const loadMore = () => {
		if (!hasMore.value || loadingMore.value || loading.value) return;

		loadingMore.value = true;
		pageNum.value += 1;
		loadCollections().finally(() => {
			loadingMore.value = false;
		});
	};

	/**
	 * 点击帖子
	 */
	const handlePostClick = (postId) => {
		uni.navigateTo({
			url: `/pages/post/postInfo?postId=${postId}`
		});
	};

	/**
	 * 取消收藏
	 */
	const handleCancelCollect = async (postId) => {
		uni.showModal({
			title: '提示',
			content: '确定要取消收藏吗？',
			success: async (modalRes) => {
				if (modalRes.confirm) {
					try {
						const res = await mockUncollectPost(postId);

						if (res.code === 200) {
							// 从列表中移除
							collections.value = collections.value.filter(item => item.postId !== postId);
							showToast('已取消收藏', 'success');
						} else {
							showToast(res.message || '操作失败', 'error');
						}
					} catch (error) {
						console.error('取消收藏失败:', error);
						showToast('操作失败', 'error');
					}
				}
			}
		});
	};

	/**
	 * 去逛逛
	 */
	const handleGoPosts = () => {
		uni.switchTab({
			url: '/pages/post/post'
		});
	};

	// 页面加载
	onMounted(() => {
		loadCollections();
	});
</script>

<style lang="scss" scoped>
	.collections-page {
		min-height: 100vh;
		background-color: #f5f5f5;

		.scroll-container {
			height: 100vh;
			padding: 20rpx;
		}
	}

	// 骨架屏
	.skeleton-container {
		.skeleton-item {
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.skeleton-content {
				.skeleton-title {
					height: 36rpx;
					background-color: #f0f0f0;
					border-radius: 4rpx;
					margin-bottom: 20rpx;
					width: 80%;
				}

				.skeleton-meta {
					display: flex;
					gap: 20rpx;

					.skeleton-text {
						height: 24rpx;
						background-color: #f0f0f0;
						border-radius: 4rpx;
						flex: 1;
					}
				}
			}

			.skeleton-animate {
				animation: skeleton-loading 1.5s ease-in-out infinite;
				background: linear-gradient(90deg,
						#f0f0f0 25%,
						#e0e0e0 50%,
						#f0f0f0 75%);
				background-size: 200% 100%;
			}
		}
	}

	// 收藏列表
	.collections-list {
		.collection-item {
			position: relative;
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			gap: 20rpx;

			.post-info {
				flex: 1;
				min-width: 0;

				.post-title {
					display: block;
					font-size: 30rpx;
					font-weight: 500;
					color: #333333;
					margin-bottom: 16rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					line-height: 1.4;
				}

				.post-meta {
					display: flex;
					flex-wrap: wrap;
					gap: 20rpx;

					.meta-item {
						display: flex;
						align-items: center;
						gap: 6rpx;

						.meta-text {
							font-size: 24rpx;
							color: #999999;
						}
					}
				}
			}

			.post-cover {
				width: 160rpx;
				height: 160rpx;
				border-radius: 12rpx;
				object-fit: cover;
				flex-shrink: 0;
			}

			.cancel-btn {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: rgba(255, 255, 255, 0.9);
				border-radius: 50%;
				box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
			}
		}
	}

	// 加载更多
	.load-more,
	.no-more {
		text-align: center;
		padding: 30rpx 0;

		.load-more-text,
		.no-more-text {
			font-size: 24rpx;
			color: #999999;
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
		gap: 20rpx;

		.empty-text {
			font-size: 28rpx;
			color: #999999;
		}

		.empty-hint {
			font-size: 24rpx;
			color: #cccccc;
			margin-bottom: 20rpx;
		}

		.go-btn {
			width: 200rpx;
		}
	}

	// 骨架屏动画
	@keyframes skeleton-loading {
		0% {
			background-position: 200% 0;
		}

		100% {
			background-position: -200% 0;
		}
	}
</style>

